package com.propertree.mailer.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import com.propertree.mailer.bean.EMailPartyInfo;
import com.propertree.mailer.bean.SenderReceiverConfig;

public class ExcelSenderReceiverInfo implements MailerSenderReceiverInfo {

	@Override
	public List<EMailPartyInfo> getSendersInfo(SenderReceiverConfig config) {
		List<EMailPartyInfo> sendersInfo = new ArrayList<EMailPartyInfo>();
		readExcel(sendersInfo, config.getSenderFilePath());
		return sendersInfo;
	}

	@Override
	public List<EMailPartyInfo> getReceiversInfo(SenderReceiverConfig config) {
		List<EMailPartyInfo> receiversInfo = new ArrayList<EMailPartyInfo>();
		readExcel(receiversInfo, config.getReceiverFilePath());
		return receiversInfo;
	}

	private void readExcel(Collection<EMailPartyInfo> emailPartyInfoCollection,
			String excelFilePath) {
		try {
			FileInputStream file = new FileInputStream(new File(excelFilePath));
			// Get the workbook instance for XLS file
			HSSFWorkbook workbook = new HSSFWorkbook(file);
			// Get first sheet from the workbook
			HSSFSheet sheet = workbook.getSheetAt(0);
			// Iterate through each rows from first sheet
			Iterator<Row> rowIterator = sheet.iterator();
			while (rowIterator.hasNext()) {
				Row row = rowIterator.next();
				// For each row, iterate through each columns
				Iterator<Cell> cellIterator = row.cellIterator();
				EMailPartyInfo emailPartyInfo = new EMailPartyInfo();
				while (cellIterator.hasNext()) {
					Cell cell = cellIterator.next();
					if (cell.getColumnIndex() == 0) {
						emailPartyInfo.setEmailId(cell.getStringCellValue());
					} else if (cell.getColumnIndex() == 1) {
						emailPartyInfo.setUserName(cell.getStringCellValue());
					} else if (cell.getColumnIndex() == 2) {
						emailPartyInfo.setPassword(cell.getStringCellValue());
					}
				}
				emailPartyInfoCollection.add(emailPartyInfo);
			}
			file.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
